import logging
import datetime
import dbtool
import time
import os

# 设置日志
def set_log(task_id):
    log_name = str(task_id) + '-' + str(int(datetime.datetime.now().timestamp())) + '.log'
    log_path = os.path.join(os.getcwd(), 'log', log_name)
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    file = logging.FileHandler(filename=log_path)
    file_format = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s",
                                    datefmt='%Y-%m-%d %H:%M:%S')
    file.setFormatter(file_format)
    logging.getLogger().addHandler(file)
    return log_name, log_path, file

#插入数据一条日志记录
def new_log(task_id, log_name):
    dao = dbtool.Dao()
    this_id = int(time.time())
    log_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    log_dict = {'id': str(this_id), 'task_id': str(task_id), 'log_time': log_time,
                'log_name': log_name}
    dao.insert_from_dict('t_training_log', log_dict)

#查找log表,判断表是否为空
def query_log(task_id):
    dao = dbtool.Dao()
    sql = 'select * from t_training_log where task_id = {}'.format(task_id)
    data = dao.query_data(sql = sql)
    return data.empty

#如果移除正在排队的task，日志
def stop_task_log(task_id, log_name, file):
    logging.info('{task} is removed'.format(task = task_id))
    logging.getLogger().removeHandler(file)
    dao = dbtool.Dao()
    this_id = int(time.time())
    log_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    log_dict = {'id': str(this_id), 'task_id': str(task_id), 'log_time': log_time,
                'log_name': log_name}
    dao.insert_from_dict('t_training_log', log_dict)



